import { EntityTypes } from "@minecraft/server";
import { Dimensions } from "@sapi-game/constants";
import { GameComponent } from "@sapi-game/main";
import { RandomUtils } from "@sapi-game/utils";
import { EffectIds } from "@sapi-game/utils/vanila-data";
import { PillarOFFortunePlayer } from "../module";
import { PillarOfFortuneMainState } from "../states/mainState";
import { PillarOfFortuneBorder } from "./border";

export class PillarOfFortuneEventActuator extends GameComponent<PillarOfFortuneMainState> {
    override onAttach(): void {}

    //箭雨
    arrowRain() {
        this.runner.run(async (r) => {
            await r.wait(20);
            for (let i = 0; i < 8; i++) {
                this.context.players.forEach((p) => {
                    if (!p.alive) return;
                    this.GenArrowForPlayer(p, 12);
                });
                await r.wait(7);
            }
        });
    }

    private GenArrowForPlayer(player: PillarOFFortunePlayer, cnt: number) {
        if (!player.player) return;
        const center = player.player.location;
        const top = this.context.map.region.getMax().y + 2;
        const arrow = EntityTypes.get("minecraft:arrow")!;
        for (let k = 0; k < cnt; k++) {
            const entity = Dimensions.Overworld.spawnEntity(arrow, {
                x: center.x + (Math.random() - 0.5) * 8,
                y: top,
                z: center.z + (Math.random() - 0.5) * 8,
            });
            entity.applyImpulse({
                x: (Math.random() - 0.25) * 0.1,
                y: -0.5,
                z: (Math.random() - 0.25) * 0.1,
            });
        }
    }

    /**恶魂来袭 */
    Ghast() {
        const center = this.context.map.center;
        const entity = Dimensions.Overworld.spawnEntity("ghast", center);
        entity.addEffect(EffectIds.Resistance, 100000, {
            amplifier: 255,
            showParticles: false,
        });
    }

    /**交换玩家 */
    swapPlayer() {
        const players = this.context.players.filter(
            (p) => p.isValid && p.alive
        );
        RandomUtils.shuffleInPlace(players);
        const loc = players.map((p) => p.player!.location);
        for (let i = 0; i < players.length; i++) {
            players[i].player?.teleport(loc[(i + 1) % players.length]);
        }
    }

    /**闪电 */
    LightningBlot() {
        this.context.players.forEach((p) => {
            if (p.alive) {
                p.player.dimension.spawnEntity(
                    "lightning_bolt",
                    p.player.location
                );
            }
        });
    }

    borderShrink() {
        this.state.getComponent(PillarOfFortuneBorder).startShrink();
    }
}
